package de.slothsoft.wasbinich.swingclient.io;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

import javax.imageio.ImageIO;
import javax.xml.bind.DatatypeConverter;

import de.slothsoft.wasbinich.core.FullPicture;
import de.slothsoft.wasbinich.core.WasBinIch;

public final class ImageUtil {

    public static FullPicture createPictureFromFile(File sectionFile) throws IOException {
	FullPicture picture = new FullPicture();
	picture.correctAnswers_en = sectionFile.getName();
	picture.section = convertFileToString(sectionFile);
	return picture;
    }

    public static String convertFileToString(File file) throws IOException {
	if (file == null)
	    return null;
	return DatatypeConverter.printBase64Binary(Files.readAllBytes(file.toPath()));
    }

    public static String shrinkImageforUpload(String imageData) throws IOException {
	return shrinkImageforUpload(imageData, WasBinIch.PICTURE_SIZE, WasBinIch.PICTURE_SIZE);
    }

    protected static String shrinkImageforUpload(String imageData, int width, int height) throws IOException {
	Image image = convertStringToImage(imageData);
	BufferedImage shrinkedImage = resize(image, width, height);

	try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
	    ImageIO.write(shrinkedImage, "jpg", out);
	    return DatatypeConverter.printBase64Binary(out.toByteArray());
	}
    }

    public static BufferedImage convertStringToImage(String imageData) {
	try {
	    byte[] rawBytes = DatatypeConverter.parseBase64Binary(imageData);
	    try (InputStream in = new ByteArrayInputStream(rawBytes);) {
		return ImageIO.read(in);
	    }
	} catch (IOException e) {
	    throw new InternalError(e.getMessage());
	}
    }

    public static BufferedImage resize(Image source, int newWidth, int newHeight) {
	BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
	Graphics g = bufferedImage.createGraphics();
	g.drawImage(source, 0, 0, newWidth, newHeight, null, null);
	return bufferedImage;
    }

    public static void writeImageToFile(RenderedImage source, File file, String format) throws FileNotFoundException,
	    IOException {
	try (FileOutputStream out = new FileOutputStream(file)) {
	    ImageIO.write(source, format, out);
	}
    }

    private ImageUtil() {
	// hit me baby one more time
    }
}
